package com.topnav.mc.uitls;

import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 字符符替换工具
 */
public class PlaceholderUtil {

    /**
     * 如：原文 123{abc}345,要用 ABC 要替换 {abc} 则写成：replaceAll("123{abc}345","{abc}","ABC")
     * @param replacement
     * @param source
     * @param target
     * @return
     */
    public static String replaceAll(String replacement,String source,String target){
        String result = replacement;
        if (source.contains("{")){source = source.replace("{", "\\{");}
        if (source.contains("}")){source = source.replace("}", "\\}");}
        if (StringUtils.isEmpty(target)){target="";}
        return replacement.replaceAll(source, target);
    }

    /**
     * 如：原文 123{abc}345,要用 ABC 要替换 {abc} 则写成：replaceAll("123{abc}345","{abc}","ABC")
     * @param replacement 原句子
     * @param source  被取代的字符串
     * @param target 取代字符串
     * @return
     */

    /**
     * 同时更新多个
     *
     * @param replacement  原句子
     * @param params  key:被取代的字符串, value :取代字符串
     * @return
     */
    public static String replaceAll(String replacement, Map<String,String> params){
        String result = replacement;
        for(Map.Entry<String,String> param : params.entrySet()){
            result = replaceAll(result,param.getKey(),param.getValue());
        }
        return result;
/*

        if (source.contains("{")){source = source.replace("{", "\\{");}
        if (source.contains("}")){source = source.replace("}", "\\}");}
        if (StringUtils.isEmpty(target)){target="";}
        return replacement.replaceAll(source, target);
*/
    }


    private static String format(String source,String ... args){
        return String.format(source, args);
    }
}
